//
//  HomePageTesttingController.m
//  LearnObjectiveC
//
//  Created by 吴可高 on 16/9/1.
//  Copyright © 2016年 吴可高. All rights reserved.

@interface KCMImageData : NSObject

@property (copy, nonatomic) NSNumber * number;
@property (strong, nonatomic) NSData * imgData;

@end
@implementation KCMImageData

@end



#import "OOThread.h"
#import "HomePageTesttingController.h"
@interface HomePageTesttingController ()
{
    OOThread * _thread;
}
@property (strong, nonatomic) NSMutableArray <UIImageView*> * imgViews;
@property (strong, nonatomic) UIButton * loadThreadButton;

@end
@implementation HomePageTesttingController
-(void)viewDidLoad
{
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor lightGrayColor];
    [self setObjectView];
    /*
    __NSLogRect(self.view.frame);
    __NSLogPoint(self.view.layer.position);
    __NSLogSize(self.view.frame.size);
    */
//    __NSLogRect(self.view.frame);

}

-(void)setObjectView
{
    //如何区分常量指针 和 指针常量
    // (1), *(指针)，const(常量),谁在前面读谁，
    // (2), *象征着地址，const 象征着内容，
    // (3), 谁在前面谁就不允许改变
    // algorithmProcessors();
    __weak  typeof(self)weakSelf  = self;
    __block CGFloat margin = 20.f;
    [self.view addSubview:self.loadThreadButton];
    [self.loadThreadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(kScreen_Width /3.f, 1*margin));
        make.centerX.mas_equalTo(weakSelf.view.mas_centerX);
        make.top.mas_equalTo(weakSelf.view.mas_top).with.offset(3*margin);
    }];
    
    for ( int i = 0; i < 12; i++) {
        UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectZero];
        imgView.contentMode = UIViewContentModeScaleToFill;
        imgView.layer.masksToBounds = YES;
        imgView.layer.borderColor = [UIColor whiteColor].CGColor;
        imgView.layer.borderWidth = 1.f;
        imgView.backgroundColor = [UIColor whiteColor];
        [self.imgViews addObject:imgView];
        [self.view addSubview:imgView];
    }
    __block UIImageView * verticalImgView = nil;
    __block UIImageView * horizontalImgView = nil;
    __block NSInteger i,j;
    [self.imgViews enumerateObjectsUsingBlock:^(UIImageView * imgView, NSUInteger idx, BOOL * _Nonnull stop) {
        [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo(CGSizeMake(85, 85));
            i = idx %3;
            j = idx /3;
            if (i==0 && j==0) {
                verticalImgView = nil;
                horizontalImgView = nil;
                make.left.mas_equalTo(weakSelf.view.mas_left).with.offset(margin/2.f);
                make.top.mas_equalTo(weakSelf.loadThreadButton.mas_bottom).with.offset(margin/2.f);
            }
            if (i != 0&& j==0) {
                verticalImgView = nil;
                horizontalImgView = weakSelf.imgViews[i-1];
                make.left.mas_equalTo(horizontalImgView.mas_right).with.offset(margin/2.f);
                make.top.mas_equalTo(weakSelf.loadThreadButton.mas_bottom).with.offset(margin/2.f);
            }
            if (i==0&&j!=0) {
                horizontalImgView = nil;
                verticalImgView = weakSelf.imgViews[(j-1)*3 +i];
                make.left.mas_equalTo(weakSelf.view.mas_left).with.offset(margin/2.f);
                make.top.mas_equalTo(verticalImgView.mas_bottom).with.offset(margin/2.f);
            }
            if (i!=0&&j!=0) {
                horizontalImgView = weakSelf.imgViews[(j-1)*3 +i-1];
                verticalImgView = weakSelf.imgViews[(j-1)*3 +i];
                make.left.mas_equalTo(horizontalImgView.mas_right).with.offset(margin/2.f);
                make.top.mas_equalTo(verticalImgView.mas_bottom).with.offset(margin/2.f);
            }
        
        }];
    }];
}

-(NSData *)requestData{
    NSURL *url=[NSURL URLWithString:@"https://www.baidu.com/img/bd_logo1.png"];
    NSData *data=[NSData dataWithContentsOfURL:url];
    return data;
}

-(void)updateImage:(KCMImageData *)imageData{
    
    NSData * imgData = imageData.imgData;
    NSNumber * index = imageData.number;
    UIImage *image=[UIImage imageWithData:imgData];
    UIImageView * imgeView = self.imgViews[[index integerValue]];
    imgeView.image = image;
}
-(void)loadImage:(NSNumber*)number
{
    NSData * data =  [self requestData];
    KCMImageData * kcmImgData = [[KCMImageData alloc]init];
    kcmImgData.imgData = data;
    kcmImgData.number = number;
    //在主线程请求数据
    [[NSOperationQueue mainQueue]addOperationWithBlock:^{
        [self updateImage:kcmImgData];
    }];
    dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
    dispatch_queue_t concurrentQueue = dispatch_queue_create("concurrent", DISPATCH_QUEUE_CONCURRENT);
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_semaphore_t  _semaphore = dispatch_semaphore_create(1);
    dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    /**
     *
     */
    dispatch_semaphore_signal(_semaphore);
    //
    NSLock * lock  = [[NSLock alloc]init];
    [lock lock];
    if ([lock tryLock]) {
        
    }
    if ([lock lockBeforeDate:[NSDate date]]) {
        
    }
    [lock unlock];
    

    
    
    
    NSCondition * condition = [[NSCondition alloc]init];
    [condition lock];
    [condition wait];
  
    
    [condition signal];
    [condition unlock];
    
    
    
    
    
    
    
}

#pragma mark IBOutlet Actions
-(void)loadData:(UIButton*)argument
{
    [self loadMultiThread];
}
-(void)loadMultiThread
{
    __weak  typeof(self)weakSelf = self;
    NSOperationQueue * operationQueue = [[NSOperationQueue alloc]init];
    operationQueue.maxConcurrentOperationCount = 20.f;
    NSBlockOperation *lastBlockOperation=[NSBlockOperation blockOperationWithBlock:^{
        [self loadImage:@(3)];
    }];
    [self.imgViews enumerateObjectsUsingBlock:^(UIImageView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSBlockOperation *blockOperation=[NSBlockOperation blockOperationWithBlock:^{
            [weakSelf loadImage:@(idx)];
        }];
        [blockOperation addDependency:lastBlockOperation];
        [operationQueue addOperations:@[blockOperation] waitUntilFinished:NO];
    }];
    [operationQueue addOperation:lastBlockOperation];
}

#pragma mark ViewController Algorithm Processor
#pragma mark ViewController Initialize SubObjectView
#pragma mark --viewController getter methods
-(UIButton *)loadThreadButton
{
    _loadThreadButton= ({
        if (!_loadThreadButton) {
            _loadThreadButton  = [UIButton buttonWithType:UIButtonTypeCustom];
            [_loadThreadButton setTitle:@"loadThread...." forState:UIControlStateNormal];
            [_loadThreadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _loadThreadButton.layer.masksToBounds = YES;
            _loadThreadButton.layer.cornerRadius = 4.f;
            _loadThreadButton.layer.borderColor = [UIColor whiteColor].CGColor;
            _loadThreadButton.layer.borderWidth = 1.f;
            _loadThreadButton.titleLabel.font = [UIFont systemFontOfSize:13.f];
            [_loadThreadButton addTarget:self action:@selector(loadData:) forControlEvents:UIControlEventTouchUpInside];
        }
        _loadThreadButton;
    });
    return _loadThreadButton;
}

-(NSMutableArray *)imgViews
{
    _imgViews = ({
        if (!_imgViews) {
            _imgViews  = [NSMutableArray array];
        }
        _imgViews;
    });
    return _imgViews;
}

@end
